package lt.marsrutai.mobile.android.fragment;

import java.util.List;

import lt.marsrutai.mobile.android.activity.intent.FastestRoutesResultIntentHolder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

/**
 * Dialog which presents the user with a list stop names. When the entered stop
 * name in the fastest route search was similar to multiple stops, a
 * clarification is needed for the search to complete
 * 
 * @author Justas
 */
public class StopClarificationDialogFragment extends DialogFragment {
    
    /** object receiving event callbacks */
    private StopClarificationDialogListener listener;
    private int dialogId;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        FastestRoutesResultIntentHolder fastestRoutesResultIntentHolder = new FastestRoutesResultIntentHolder(getArguments());
        int title = fastestRoutesResultIntentHolder.getDialogTitle();
        final List<String> choices = fastestRoutesResultIntentHolder.getDialogChoices();
        dialogId = fastestRoutesResultIntentHolder.getDialogId();

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(title).setItems(choices.toArray(new String[choices.size()]), new OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                listener.onDialogClick(dialogId, choices.get(which));
            }
        });
        return builder.create();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            // Register parent activity as a callback listener
            this.listener = (StopClarificationDialogListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement " + StopClarificationDialogListener.class);
        }
    }
    
    @Override
    public void onCancel(DialogInterface dialog) {
        listener.onDialogCancel(dialogId);
        super.onCancel(dialog);
    }

    /**
     * Interface for receiving event callbacks
     * 
     * @author Justas
     */
    public interface StopClarificationDialogListener {

        /**
         * Called when the user performs a click on the dialog
         * 
         * @param dialogId
         * @param selectedItem  
         */
        public void onDialogClick(int dialogId, String selectedItem);
        
        /**
         * Called when the user cancels the dialog
         * 
         * @param dialogId
         * @param selectedItem  
         */
        public void onDialogCancel(int dialogId);

    }
}